package com.yjc.drygoods.product.app;

import java.io.Console;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.yjc.common.constant.EsConstant;
import com.yjc.common.to.SkuEsModel;
import com.yjc.common.utils.PageUtils;
import com.yjc.drygoods.product.config.DryGoodsElasticSearchConfig;
import com.yjc.drygoods.product.entity.SpuInfoEntity;
import com.yjc.drygoods.product.service.CategoryService;
import com.yjc.drygoods.product.service.impl.Recommend;
import com.yjc.drygoods.product.vo.EChartsAttentionCountVo;
import com.yjc.drygoods.product.vo.EChartsSaleCountVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.yjc.drygoods.product.entity.SkuInfoEntity;
import com.yjc.drygoods.product.service.SkuInfoService;
import com.yjc.common.utils.R;


/**
 * sku信息
 *
 * @author yjc
 * @email yjc19979401754@126.com
 * @date 2022-08-19 21:27:48
 */
@Slf4j
@RestController
@RequestMapping("product/skuinfo")
public class SkuInfoController {
    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    Recommend recommend;

    @Autowired
    RestHighLevelClient client;

    @Autowired
    CategoryService categoryService;

    /**
     * 修改sku干货价格(购物车中的和es中的也要修改)
     *
     * @param price
     * @return
     */
    @GetMapping("/update/skuPrice")
    public R updateSkuPrice(@RequestParam("price") BigDecimal price, @RequestParam("skuId") Long skuId) {
        log.info("price:{}", price);
        skuInfoService.updateSkuInfoPrice(price, skuId);
        return R.ok();
    }

    /**
     * 修改降价价格
     *
     * @param spuId
     * @param reducedPrice 降低的价格（不是降价，需要从原价减去reducedPrice，才能得到降价）
     * @return
     */
    @GetMapping("/update/reducedPrice")
    public R updateReducedPrice(@RequestParam Long spuId, @RequestParam BigDecimal reducedPrice) {
        skuInfoService.updateReducedPrice(spuId, reducedPrice);
        return R.ok();
    }

    /**
     * 获取所有该用户可能喜欢的商品
     *
     * @param username
     * @return
     */
    @GetMapping("/get/user/like/skuInfo")
    public R getUserLikeSkuInfo(@RequestParam(value = "username", required = false) String username) throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(EsConstant.PRODUCT_INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.size(1000);
        searchRequest.source(sourceBuilder);
        SearchResponse response = client.search(searchRequest, DryGoodsElasticSearchConfig.COMMON_OPTIONS);
        SearchHits hits = response.getHits();
        SearchHit[] hits1 = hits.getHits();
        List<Long> skuIds = Arrays.stream(hits1).map(item -> {
            String sourceAsString = item.getSourceAsString();
            SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
            return skuEsModel.getSkuId();
        }).collect(Collectors.toList());
        if (username != null) {
            List<SkuInfoEntity> skuInfoEntities = recommend.guessUserLike(username, skuIds);
            if (skuInfoEntities != null && skuInfoEntities.size() > 0) {
                return R.ok().setData(skuInfoEntities);
            }
        }
        Map<String, Object> params = new HashMap<>();
        params.put("page", "1");
        params.put("limit", "4");
        PageUtils pageUtils = skuInfoService.queryPage(params);
        List<SkuInfoEntity> list = ((List<SkuInfoEntity>) pageUtils.getList()).stream().filter(e -> skuIds.contains(e.getSkuId())).collect(Collectors.toList());
        return R.ok().setData(list);
    }

    /**
     * 更新对应sku商品关注量
     *
     * @param params
     * @return
     */
    @RequestMapping("/update/attentionCount")
    R updateAttentionCount(@RequestParam Map<String, Object> params) {
        skuInfoService.updateAttentionCount(params);
        return R.ok();
    }

    /**
     * 获取所有sku商品数据(eChart专用)
     *
     * @return
     */
    @GetMapping("/get/allSkuInfo")
    public R getAllSkuInfo() {
        List<SkuInfoEntity> list = skuInfoService.list();
        log.info("list:{}", list);
        return R.ok().put("result", list);
    }

    @GetMapping("/get/two/year/attentions")
    public R getTwoYearAttentions() {
        Map<String, List<EChartsAttentionCountVo>> resMap = null;
        try {
            resMap = skuInfoService.getTwoYearAttentions();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("resMap:{}", resMap);
        return R.ok().put("result", resMap);
    }

    /**
     * 销量分析：分析前5天中每种干货销量
     *
     * @param
     * @return
     */
    @GetMapping("/get/seven/five/drygoods")
    public R getSevenFiveDrygoods() {
        Map<String, List<EChartsSaleCountVo>> resMap = null;
        try {
            resMap = skuInfoService.getSevenFiveDrygoods();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        log.info("resMap:{}", resMap);
        return R.ok().put("result", resMap);
    }

    @PostMapping("/getBatch/skuInfo")
    public R getBatchSkuInfo(@RequestBody List<Long> skuIds) {
        List<SkuInfoEntity> skuInfos = skuInfoService.getBatchSkuInfo(skuIds);
        return R.ok().setData(skuInfos);
    }

    /**
     * 修改
     */
    @PostMapping("/update/skuSaleCount")
    public R updateSkuSaleCount(@RequestBody List<SkuInfoEntity> skuInfos) {
        if (skuInfos != null) {
            skuInfoService.updateSkuSaleCount(skuInfos);
        }
        return R.ok();
    }

    @GetMapping("/getSpuInfo/by/{skuId}")
    public R getSpuInfoBySkuId(@PathVariable("skuId") Long skuId) {
        SpuInfoEntity spuInfo = skuInfoService.getSpuInfoBySkuId(skuId);
        return R.ok().setData(spuInfo);
    }

    /**
     * /product/skuinfo/list
     * sku检索
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = skuInfoService.queryPageByCondition(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{skuId}")
    public R info(@PathVariable("skuId") Long skuId) {
        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        Long[] catelogPath = categoryService.findCatelogPath(skuInfo.getCatalogId());
        skuInfo.setCatelogPath(catelogPath);
        log.info("skuInfo:{}", skuInfo);
        for (Long aLong : catelogPath) {
            System.out.println(aLong);
        }
        return R.ok().put("skuInfo", skuInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody SkuInfoEntity skuInfo) {
        skuInfoService.save(skuInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody SkuInfoEntity skuInfo) {
        skuInfoService.updateById(skuInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] skuIds) {
        skuInfoService.removeByIds(Arrays.asList(skuIds));

        return R.ok();
    }

}
